use dioxus::prelude::*;

#[cfg(target_arch = "wasm32")]
use gloo_net::http::Request;

use crate::backend::save_dog;
use crate::DogApi;
use crate::Route;

const DOG_API_URL: &str = "https://dog.ceo/api/breeds/image/random";
const FALLBACK_IMAGE: &str =
    "https://cdn.pixabay.com/photo/2016/10/26/22/02/dog-1772759_1280.jpg";

#[component]
pub fn Dogview() -> Element {
    let mut img_src = use_resource(|| async move {
        match fetch_random_dog_image().await {
            Ok(url) => url,
            Err(err) => {
                tracing::error!("获取狗狗图片失败: {err}");
                FALLBACK_IMAGE.to_string()
            }
        }
    });

    let on_skip = move |_| {
        tracing::info!("用户点击跳过按钮，获取新图片...");
        img_src.restart();
    };

    let on_save = move |_| {
        tracing::info!("用户点击保存按钮，保存当前图片");
        if let Some(image) = img_src.cloned() {
            spawn(async move {
                if let Err(err) = save_dog(image).await {
                    tracing::error!("保存图片失败: {err}");
                }
            });
        } else {
            tracing::warn!("当前没有加载好的图片，忽略保存请求");
        }
        img_src.restart();
    };

    rsx! {
        div { id: "dogview",
            img { src: img_src.cloned().unwrap_or_default() }
        }
        div { id: "buttons",
            button { onclick: on_skip, id: "skip", "skip" }
            button { onclick: on_save, id: "save", "save!" }
        }
    }
}

#[component]
pub fn PageNotFound(segments: Vec<String>) -> Element {
    let path = if segments.is_empty() {
        "/".to_string()
    } else {
        format!("/{}", segments.join("/"))
    };

    rsx! {
        div { id: "not-found",
            h1 { "404" }
            p { "找不到页面: {path}" }
            Link { to: Route::Dogview, "返回首页" }
        }
    }
}

#[cfg(target_arch = "wasm32")]
async fn fetch_random_dog_image() -> Result<String, String> {
    Request::get(DOG_API_URL)
        .send()
        .await
        .map_err(|err| format!("请求失败: {err}"))?
        .json::<DogApi>()
        .await
        .map(|response| response.message)
        .map_err(|err| format!("解析响应失败: {err}"))
}

#[cfg(not(target_arch = "wasm32"))]
async fn fetch_random_dog_image() -> Result<String, String> {
    reqwest::get(DOG_API_URL)
        .await
        .map_err(|err| format!("请求失败: {err}"))?
        .json::<DogApi>()
        .await
        .map(|response| response.message)
        .map_err(|err| format!("解析响应失败: {err}"))
}
